<template>
  <div class="user-management-container">
    <!-- 加载状态 -->
    <div v-if="isLoading" class="loading-container">
      <el-skeleton animated :rows="6" />
    </div>

    <!-- 用户个人资料区域 -->
    <div v-else class="profile-section">
      <div class="profile-header">
        <h2><i class="el-icon-user"></i> 个人资料</h2>
      </div>

      <div class="profile-content">
        <!-- 用户头像和信息展示 -->
        <div class="profile-display">
          <div class="avatar-container">
            <el-avatar :size="100" :src="userProfile.avatar || defaultAvatar" />
            <div class="avatar-overlay" @click="showAvatarTip">
              <span>更改头像</span>
            </div>
          </div>

          <div class="profile-info">
            <h3>{{ userProfile.name || userProfile.username || '未设置姓名' }}</h3>
            <p class="info-item"><i class="el-icon-message"></i> {{ userProfile.email || '未设置邮箱' }}</p>
            <p class="info-item">
              <i class="el-icon-user"></i> {{ getUserTypeText(userProfile.userType) }}
            </p>
            <p class="info-item">
              <i class="el-icon-time"></i> 注册时间: {{ userProfile.createTime }}
            </p>

            <div class="profile-tags">
              <el-tag :type="getTagType(userProfile.userType)">
                {{ getUserTypeText(userProfile.userType) }}
              </el-tag>
              <el-tag :type="userProfile.status === 'ENABLED' ? 'danger' : 'success' ">
                {{ userProfile.status === 'ENABLED' ? '禁用' : '正常' }}
              </el-tag>
            </div>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="profile-actions">
          <el-button type="primary" @click="openForm('update')" icon="el-icon-edit">
            编辑资料
          </el-button>
          <el-button @click="openForm('password')" icon="el-icon-lock">
            修改密码
          </el-button>
          <el-button
              v-if="canDeactivate"
              type="danger"
              @click="handleDeactivateAccount"
              icon="el-icon-delete"
          >
            注销账户
          </el-button>
        </div>
      </div>

      <!-- 编辑资料表单 -->
      <div v-if="currentForm === 'update'" class="profile-form">
        <h3><i class="el-icon-edit"></i> 编辑个人资料</h3>

        <el-form
            :model="updateForm"
            label-width="100px"
            :rules="updateRules"
            ref="updateFormRef"
        >
          <!-- 移除不可修改的username字段 -->
          <el-form-item label="用户名">
            <el-input :value="userProfile.username" disabled />
          </el-form-item>

          <el-form-item label="姓名" prop="name">
            <el-input v-model="updateForm.name" placeholder="请输入您的姓名" />
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input v-model="updateForm.email" placeholder="请输入您的邮箱" />
          </el-form-item>

          <el-form-item label="头像URL" prop="avatar">
            <el-input v-model="updateForm.avatar" placeholder="请输入头像URL" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" :loading="isUpdating" @click="handleUpdateUserProfile">
              保存更改
            </el-button>
            <el-button @click="closeForm()">取消</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 修改密码表单 -->
      <div v-if="currentForm === 'password'" class="profile-form">
        <h3><i class="el-icon-lock"></i> 修改密码</h3>
        <el-form
            :model="passwordForm"
            label-width="100px"
            :rules="passwordRules"
            ref="passwordFormRef"
        >
          <el-form-item label="当前密码" prop="currentPassword">
            <el-input
                v-model="passwordForm.currentPassword"
                type="password"
                show-password
                placeholder="请输入当前密码"
            />
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input
                v-model="passwordForm.newPassword"
                type="password"
                show-password
                placeholder="至少8位字符"
            />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
                v-model="passwordForm.confirmPassword"
                type="password"
                show-password
                placeholder="再次输入新密码"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :loading="isChangingPassword" @click="handleChangePassword">
              更新密码
            </el-button>
            <el-button @click="closeForm()">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getCurrentUserProfile,
  updateUserProfile,
  changePassword,
  deactivateAccount
} from '@/api/profile'
import { useRouter } from 'vue-router'

const authStore = useAuthStore()
const router = useRouter()
const defaultAvatar = 'https://picsum.photos/200/200?random=user'

// 用户资料数据
const userProfile = ref({})
const currentForm = ref(null)
const isUpdating = ref(false)
const isChangingPassword = ref(false)
const isLoading = ref(true)

// 更新资料表单
const updateForm = ref({
  username: '',
  name: '',
  email: '',
  avatar: ''
})

// 密码表单
const passwordForm = ref({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const updateRules = reactive({
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ]
})

const passwordRules = reactive({
  currentPassword: [{ required: true, message: '请输入当前密码', trigger: 'blur' }],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 8, message: '密码至少8个字符', trigger: 'blur' },
    {
      validator: (_, val) => /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/.test(val) ||
          '密码需包含大小写字母和数字',
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (_, val) => val === passwordForm.value.newPassword || '两次输入的密码不一致',
      trigger: 'blur'
    }
  ]
})

// 计算属性
const canDeactivate = computed(() => {
  return authStore.isAuthenticated &&
      authStore.user?.userId === userProfile.value?.userId &&
      userProfile.value?.userType !== 'ADMIN'
})

// 获取用户类型文本
const getUserTypeText = (type) => {
  const types = {
    ADMIN: '管理员',
    TEACHER: '教师',
    STUDENT: '学生'
  }
  return types[type] || '未知'
}

// 获取标签类型
const getTagType = (type) => {
  return {
    ADMIN: 'danger',
    TEACHER: 'warning',
    STUDENT: 'success'
  }[type] || 'info'
}

// 显示头像提示
const showAvatarTip = () => {
  ElMessage.info('请上传头像URL地址')
}

// 获取用户资料
// 获取用户资料
const fetchUserProfile = async () => {
  try {
    isLoading.value = true
    const response = await getCurrentUserProfile()
    userProfile.value = response.data || {}

    // 初始化表单数据 - 只包含可修改字段
    updateForm.value = {
      name: userProfile.value.name || '',
      email: userProfile.value.email || '',
      avatar: userProfile.value.avatar || ''
    }
  } catch (error) {
    console.error('获取用户资料失败:', error)
    handleApiError(error, '获取用户资料失败')
    if (error.response?.status === 401) {
      await authStore.logout()
      router.push('/login')
    }
  } finally {
    isLoading.value = false
  }
}

// 更新用户资料
const handleUpdateUserProfile = async () => {
  try {
    await updateFormRef.value.validate()

    isUpdating.value = true

    // 创建只包含可修改字段的请求数据
    const requestData = {
      // 从表单获取可修改字段
      name: updateForm.value.name,
      email: updateForm.value.email,
      avatar: updateForm.value.avatar,

      // 保留原有的不可修改字段
      userId: userProfile.value.userId,
      username: userProfile.value.username,
      userType: userProfile.value.userType,
      status: userProfile.value.status,
      createTime: userProfile.value.createTime
    }

    const response = await updateUserProfile(requestData)

    // 更新本地数据
    userProfile.value = { ...userProfile.value, ...response.data }
    // 更新authStore中的用户数据
    if (authStore.user) {
      authStore.user = { ...authStore.user, ...response.data }
    }

    ElMessage.success('资料更新成功')
    closeForm()
  } catch (error) {
    console.error('更新资料失败:', error)
    if (error.name !== 'ValidateError') {
      handleApiError(error, '更新资料失败')
    }
  } finally {
    isUpdating.value = false
  }
}

// 修改密码
const handleChangePassword = async () => {
  try {
    await passwordFormRef.value.validate()

    isChangingPassword.value = true
    await changePassword({
      currentPassword: passwordForm.value.currentPassword,
      newPassword: passwordForm.value.newPassword
    })

    ElMessage.success('密码修改成功，请重新登录')
    passwordForm.value = { currentPassword: '', newPassword: '', confirmPassword: '' }
    closeForm()
    await authStore.logout()
    router.push('/login')
  } catch (error) {
    console.error('修改密码失败:', error)
    if (error.name !== 'ValidateError') {
      handleApiError(error, '修改密码失败')
    }
  } finally {
    isChangingPassword.value = false
  }
}

// 注销账户
const handleDeactivateAccount = async () => {
  try {
    await ElMessageBox.confirm(
        '确定要注销您的账户吗？此操作将永久删除您的所有数据且不可恢复。',
        '确认注销账户',
        {
          confirmButtonText: '确认注销',
          cancelButtonText: '取消',
          type: 'warning',
          confirmButtonClass: 'el-button--danger'
        }
    )

    await deactivateAccount()
    ElMessage.success('账户已成功注销')
    await authStore.logout()
    router.push('/login')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('注销账户失败:', error)
      handleApiError(error, '注销账户失败')
    }
  }
}

// 处理API错误
const handleApiError = (error, defaultMessage) => {
  if (error.response) {
    const status = error.response.status
    const data = error.response.data

    switch (status) {
      case 400:
        ElMessage.error(data.message || '请求参数错误')
        break
      case 401:
        ElMessage.error('会话已过期，请重新登录')
        authStore.logout()
        router.push('/login')
        break
      case 403:
        ElMessage.error('没有权限执行此操作')
        break
      case 404:
        ElMessage.error('资源不存在')
        break
      default:
        ElMessage.error(data.message || defaultMessage)
    }
  } else {
    ElMessage.error(defaultMessage)
  }
}

// 表单引用
const updateFormRef = ref(null)
const passwordFormRef = ref(null)

// 打开表单
const openForm = (formType) => {
  currentForm.value = formType
}

// 关闭表单
const closeForm = () => {
  currentForm.value = null
}

// 初始化
onMounted(async () => {
  try {
    // 确保authStore已初始化
    if (!authStore.isInitialized) {
      await authStore.initialize()
    }

    if (!authStore.isAuthenticated) {
      router.push('/login')
      return
    }

    await fetchUserProfile()
  } catch (error) {
    console.error('初始化失败:', error)
    ElMessage.error('初始化失败，请刷新页面')
    router.push('/login')
  }
})
</script>

<style scoped>
.user-management-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.loading-container {
  padding: 40px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.profile-section {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 24px;
}

.profile-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.profile-header h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.profile-content {
  display: flex;
  flex-direction: column;
}

.profile-display {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
}

.avatar-container {
  position: relative;
  margin-right: 30px;
  cursor: pointer;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
  border-radius: 50%;
}

.avatar-container:hover .avatar-overlay {
  opacity: 1;
}

.profile-info {
  flex: 1;
}

.profile-info h3 {
  margin: 0 0 12px 0;
  font-size: 24px;
  color: #303133;
}

.info-item {
  margin: 0 0 8px 0;
  color: #606266;
  font-size: 14px;
}

.profile-tags {
  display: flex;
  gap: 8px;
  margin-top: 12px;
}

.profile-actions {
  display: flex;
  gap: 12px;
  margin-top: 20px;
}

.profile-form {
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #ebeef5;
}

.profile-form h3 {
  margin: 0 0 20px 0;
  font-size: 18px;
  color: #303133;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-icon-user,
.el-icon-message,
.el-icon-phone,
.el-icon-edit,
.el-icon-lock,
.el-icon-delete,
.el-icon-time {
  margin-right: 8px;
}

@media (max-width: 768px) {
  .profile-display {
    flex-direction: column;
    align-items: flex-start;
  }

  .avatar-container {
    margin-right: 0;
    margin-bottom: 16px;
  }

  .profile-actions {
    flex-wrap: wrap;
  }
}
</style>